//
//  IGEditPictureListVC.m
//  jingdongfang
//
//  Created by RKL on 2018/5/21.
//  Copyright © 2018年 BOE-SBG-CTO. All rights reserved.
//

#import "IGEditPictureListVC.h"
#import "EditPictureListTagView.h"
#import "PictureListSelectLabelView.h"
#import "UpPrintVC.h"
#import "IGSelectDrawVC.h"
#import "IGPictureListDetailVC.h"
#import "IGCreatListApi.h"
#import "ClickImageViewController.h"
#import "IGOSSManager.h"

#define AutoHeight(height) height*(KSCREENWIDTH/375.0f)

@interface IGEditPictureListVC ()<EditPictureListTagViewDelegate,UITextViewDelegate>
{
    BOOL isShow;
   
}
/**
 底部的scrollView
 */
@property (nonatomic , strong) UIScrollView * bottomScrollView;

@property (nonatomic , strong) UIImageView * coverImageView;

@property (nonatomic , strong) UITextField * nameTextField;

@property (nonatomic , strong) EditPictureListTagView * tagLabelView;

/**
 数据源
 */
@property (nonatomic , strong) NSMutableArray * dataSourceArray;

/**
 个人简介的输入框
 */
@property (nonatomic , strong) UITextView * personInfoTextView;
/**
 显示字数多少的Label
 */
@property (nonatomic , strong) UILabel * stirngLenghLabel;
/**
 默认字体
 */
@property (nonatomic , strong) UILabel * placeHolder;


@property (nonatomic , strong) PictureListSelectLabelView * pictureListSelectView;
@property (nonatomic , strong) IGArtLibraryApi * artLibraryApi;
@property (nonatomic , strong) NSMutableArray * artLibraryArr;
@property (nonatomic, strong) IGCreatListApi * creatListApi;

@property (nonatomic, strong) UIImage * changeImage;
@end

@implementation IGEditPictureListVC

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"编辑画单信息";
    self.view.backgroundColor = RGB(242, 244, 248);
    UIBarButtonItem * right = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(sureClick:)];
    [right setTitleTextAttributes:@{NSForegroundColorAttributeName : RGB(0, 171, 230)} forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = right;
    [self.view addSubview:self.bottomScrollView];

    [[IGOSSManager sharedManager] requestOssToken:IGAliYunFolderTypeDrawList];

    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    //设置成NO表示当前控件响应后会传播到其他控件上，默认为YES。
    tapGestureRecognizer.cancelsTouchesInView = NO;
    //将触摸事件添加到view上
    [self.bottomScrollView addGestureRecognizer:tapGestureRecognizer];
    
    [self dataRequest];
    
    [self privateBuildUI];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tongzhi:) name:@"EditDrawPic" object:nil];
}

#pragma mark - 通知过来的
- (void)tongzhi:(NSNotification *)notification
{
    NSLog(@"%@",notification);
    self.coverImageView.image = notification.object;
}

#pragma mark - 确定按钮点击事件
- (void)sureClick:(UIBarButtonItem *)sender
{
    NSLog(@"确定按钮点击事件");
    
    [self showText:NSLocalizedString(@"Submitting", nil)];
    [[IGOSSManager sharedManager] asyncPutImages:@[self.coverImageView.image] withCompleteBlock:^(NSArray *params, NSArray *urls)
    {
        if (params.count != 0)
        {
            [self submit:params.firstObject];
        }
        else
        {
            //            [self presentMessageTips:@"提交失败"];
            [self presentMessageTips:NSLocalizedString(@"Submitting Failed", nil)];
        }
    }];
}

#pragma mark - 上传修改的内容
- (void)submit:(NSString *)imageUrl
{
    self.creatListApi.drawlistId = self.drawListId;
    self.creatListApi.image = imageUrl;
    self.creatListApi.pIds = @"";
    self.creatListApi.title = self.nameTextField.text;
    self.creatListApi.secrecy = @"";
    self.creatListApi.content = self.personInfoTextView.text;
    
    NSMutableArray * tempArr = [NSMutableArray new];
    for (int i = 0 ; i<self.dataSourceArray.count; i++)
    {
        IGArtDetailLibrary * lib = self.dataSourceArray[i];
        [tempArr addObject:lib.aId];
    }
    self.creatListApi.labels = [tempArr componentsJoinedByString:@","];
    self.creatListApi.content = self.personInfoTextView.text;
    
    if ([self.nameTextField.text isEqualToString:@""] || self.nameTextField.text == nil)
    {
        [self presentMessageTips:@"请填写画单名称"];
    }
    else if (tempArr.count == 0)
    {
        [self presentMessageTips:@"请选择画单标签"];
    }
    
    
    [self.creatListApi startWithDecodeClass:[IGCreatListResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error)
     {
         if (responseObject)
         {
             IGCreatListResp * resp = responseObject;
             if ([resp.resHeader.code isEqualToString:@"success"])
             {
                 [self.navigationController popViewControllerAnimated:YES];
             }
         }
         [self dismissLoading];
     }];
}

#pragma  mark - 构建UI
- (void)privateBuildUI
{
    //更换封面
    UIButton * coverBtn = ({
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.backgroundColor = [UIColor whiteColor];
        btn.frame = CGRectMake(0, 5, KSCREENWIDTH, 75);
        [btn addTarget:self action:@selector(coverBtnClick) forControlEvents:UIControlEventTouchUpInside];
        btn;
    });
    [self.bottomScrollView addSubview:coverBtn];
    UILabel * coverBtnTitleLabel = ({
        UILabel * label = [[UILabel alloc] init];
        label.frame = CGRectMake(15, 0, 150, 75);
        label.font = [UIFont systemFontOfSize:16];
        label.text = @"更换封面";
        label.textColor = RGB(54, 54, 54);
        label;
    });
    [coverBtn addSubview:coverBtnTitleLabel];
    UIImageView * coverRightArrowImageView = ({
        UIImageView * imageView = [[UIImageView alloc] init];
        imageView.image = [UIImage imageNamed:@"picture_right_arrow"];
        imageView.frame = CGRectMake(KSCREENWIDTH-23, 62/2, 8, 13);
        imageView.userInteractionEnabled = YES;
        imageView;
    });
    [coverBtn addSubview:coverRightArrowImageView];
    self.coverImageView = ({
        UIImageView * iamgeView = [[UIImageView alloc] init];
        iamgeView.frame = CGRectMake(CGRectGetMinX(coverRightArrowImageView.frame)-80, 5, 65, 65);
        [iamgeView sd_setImageWithURL:[NSURL URLWithString:self.drawModel.image] placeholderImage:[UIImage imageFromColor:[UIColor mainRandomColor]]];
        iamgeView;
    });
    [coverBtn addSubview:self.coverImageView];

    
    //名称
    UIView * nameView = ({
        UIView * view = [[UIView alloc] init];
        view.backgroundColor = [UIColor whiteColor];
        view.frame = CGRectMake(0, CGRectGetMaxY(coverBtn.frame)+1, KSCREENWIDTH, 60);
        view;
    });
    [self.bottomScrollView addSubview: nameView];
    UILabel * nameTitleLabel = ({
        UILabel * label = [[UILabel alloc] init];
        label.frame = CGRectMake(15, 0, 100, 75);
        label.font = [UIFont systemFontOfSize:16];
        label.text = @"名称";
        label.textColor = RGB(54, 54, 54);
        label;
    });
    [nameView addSubview:nameTitleLabel];
    self.nameTextField = ({
        UITextField * textField = [UITextField quickCreateTextFieldWithFrame:CGRectMake(KSCREENWIDTH-AutoHeight(275), 0, AutoHeight(260), 60)
                                                           placeholderString:@"VVVV"
                                                                        font:16
                                                                   textColor:RGB(54, 54, 54)];
        textField.textAlignment = NSTextAlignmentRight;
        textField;
    });
    [nameView addSubview:self.nameTextField];
    self.nameTextField.text = self.drawModel.title;
    
    //标签
    UIButton * tagView = ({
        UIButton * view = [UIButton buttonWithType:UIButtonTypeCustom];
        view.backgroundColor = [UIColor whiteColor];
        view.frame = CGRectMake(0, CGRectGetMaxY(nameView.frame)+1, KSCREENWIDTH, 60);
        [view addTarget:self action:@selector(tagViewClick) forControlEvents:UIControlEventTouchUpInside];
        view;
    });
    [self.bottomScrollView addSubview: tagView];
    UILabel * tagTitleLabel = ({
        UILabel * label = [[UILabel alloc] init];
        label.frame = CGRectMake(15, 0, 85, 60);
        label.font = [UIFont systemFontOfSize:16];
        label.text = @"标签";
        label.textColor = RGB(54, 54, 54);
        label;
    });
    [tagView addSubview:tagTitleLabel];
    UIImageView * tagRightArrowImageView = ({
        UIImageView * imageView = [[UIImageView alloc] init];
        imageView.image = [UIImage imageNamed:@"picture_right_arrow"];
        imageView.frame = CGRectMake(KSCREENWIDTH-23, 47/2, 8, 13);
        imageView.userInteractionEnabled = YES;
        imageView;
    });
    [tagView addSubview:tagRightArrowImageView];
    
    
    
    self.tagLabelView = [[EditPictureListTagView alloc] initWithFrame:CGRectMake(100, 0, KSCREENWIDTH-110-23, 60)];
    self.tagLabelView.delegate = self;
    [tagView addSubview:self.tagLabelView];

    self.dataSourceArray = self.drawModel.lstLabel;
    self.tagLabelView.dataArray = self.drawModel.lstLabel;
    [self.tagLabelView reloadeData];
    
    //画单简介
    UIView * personInfoView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(tagView.frame)+1, KSCREENWIDTH, 200)];
    personInfoView.backgroundColor = RGB(255, 255, 255);
    [self.bottomScrollView addSubview:personInfoView];
    //画单简介输入框
    self.personInfoTextView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, KSCREENWIDTH-20, 160)];
    self.personInfoTextView.scrollEnabled = NO;
    self.personInfoTextView.backgroundColor = [UIColor clearColor];
    [self.personInfoTextView setFont: [UIFont systemFontOfSize:16]];
    self.personInfoTextView.textColor = RGB(54, 54, 54);
    self.personInfoTextView.delegate = self;
    [personInfoView addSubview:self.personInfoTextView];
    //默认字体
    self.placeHolder = [UILabel creatLabelWithText:@"请输入您要更改的内容"
                                        FontOfSize:16
                                         textColor:RGB(146, 146, 146)];
    self.placeHolder.frame = CGRectMake(15, 18, AutoHeight(200), 16);
    self.placeHolder.hidden = NO;
    [personInfoView addSubview:self.placeHolder];
    //限制字数
    self.stirngLenghLabel = [UILabel creatLabelWithText:@"0/300"
                                             FontOfSize:14
                                              textColor:RGB(0, 171, 230)];
    self.stirngLenghLabel.frame = CGRectMake(0, 170, KSCREENWIDTH-20, 30);
    self.stirngLenghLabel.textAlignment = NSTextAlignmentRight;
    [personInfoView addSubview:self.stirngLenghLabel];
    
    
    
#pragma mark - PictureListSelectLabelView的回调
    @KWeakObj(self)
    self.pictureListSelectView = [[PictureListSelectLabelView alloc] initWithFrame:CGRectMake(KSCREENWIDTH, 0, KSCREENWIDTH, KSCREENHEIGHT)];
    self.pictureListSelectView.filterBlock = ^(NSMutableArray *arr)
    {
        isShow = !isShow;
        [selfWeak hideFilterView];
    };
    self.pictureListSelectView.sureBlock = ^(NSMutableArray * arr)
    {
        isShow = !isShow;
        selfWeak.tagLabelView.dataArray = arr;
        selfWeak.dataSourceArray = arr;
        [selfWeak.tagLabelView reloadeData];
        [selfWeak hideFilterView];
    };
    [[UIApplication sharedApplication].keyWindow addSubview:self.pictureListSelectView];
    isShow = NO;
    
}

#pragma mark - 更换画单封面的点击事件
- (void)coverBtnClick
{
//    ClickImageViewController * VC = [[ClickImageViewController alloc] initWithImage:[UIImage imageNamed:@"launch1"]];
//    [self.navigationController pushViewController:VC animated:YES];
    
    IGSelectDrawVC * VC = [[IGSelectDrawVC alloc] init];
    VC.dataArr = self.drawModel.productList;
    [self.navigationController pushViewController:VC animated:YES];
}

#pragma mark - 标签的请求
- (void)dataRequest
{
    self.artLibraryApi = [IGArtLibraryApi new];
    self.artLibraryApi.isCreatListLabel = YES;
    self.artLibraryArr = [@[] mutableCopy];
    @KWeakObj(self)
    [self.artLibraryApi startWithDecodeClass:[IGArtLibraryResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error)
    {
        if (responseObject)
        {
            IGArtLibraryResp *resp = responseObject;
            IGArtLibraryModel *model = resp.data;
            selfWeak.artLibraryArr = [self addSelectStrWithArr:[model.lstClass mutableCopy]];
        }
    }];
}
- (NSMutableArray *)addSelectStrWithArr:(NSMutableArray *)arr
{
    NSMutableArray *temp = [arr mutableCopy];
    for (int i = 0; i < arr.count; i++)
    {
        IGArtLibrary *lib = arr[i];
        IGArtLibrary *libTemp = temp[i];
        for (int j = 0; j < lib.lstSubClass.count; j++)
        {
            IGArtDetailLibrary *dic = libTemp.lstSubClass[j];
            dic.isSelect = @"0";
        }
    }
    return temp;
}


#pragma mark - 选择标签
- (void)tagViewClick
{
    if (_artLibraryArr.count)
    {
        self.pictureListSelectView.dataSource = self.artLibraryArr;
        [self.pictureListSelectView.collectionV reloadData];
        isShow = !isShow;
        if (isShow)
        {
            [self showFilterView];
        }
        else
        {
            [self hideFilterView];
        }
    }
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self hideFilterView];
}
#pragma mark - 显示标签选择
- (void)showFilterView
{
    [UIView animateWithDuration:0.2 animations:^{
        self.pictureListSelectView.frame = CGRectMake(0, 0, KSCREENWIDTH, KSCREENHEIGHT);
    }];
}
#pragma mark - 隐藏标签选择
- (void)hideFilterView
{
    [UIView animateWithDuration:0.2 animations:^{
        self.pictureListSelectView.frame = CGRectMake(KSCREENWIDTH, 0, KSCREENWIDTH, KSCREENHEIGHT);
    }];
}

#pragma mark - 删除标签
- (void)removeButtonTag:(NSInteger)index
{
    [self.dataSourceArray removeObjectAtIndex:index];
    self.tagLabelView.dataArray = self.dataSourceArray;
    [self.tagLabelView reloadeData];
}


#pragma mark - UITextViewDelegate
//正在改变
- (void)textViewDidChange:(UITextView *)textView
{
    if ([textView.text length] == 0)
    {
        [self.placeHolder setHidden:NO];
    }
    else
    {
        [self.placeHolder setHidden:YES];
    }
    
    //实时显示字数
    self.stirngLenghLabel.text = [NSString stringWithFormat:@"%lu/300", (unsigned long)textView.text.length];
    
    //字数限制操作
    if (textView.text.length >= 300)
    {
        textView.text = [textView.text substringToIndex:300];
        self.stirngLenghLabel.text = @"300/300";
    }
}
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    return YES;
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    
    if (textView.text.length > 300)
    {
        return NO;
    }
    else
    {
        return YES;
    }
}

#pragma mark - 懒加载
- (UIScrollView *)bottomScrollView
{
    if (_bottomScrollView == nil)
    {
        _bottomScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, NavigationMagin, KSCREENWIDTH, KSCREENHEIGHT - NavigationMagin)];
        _bottomScrollView.backgroundColor = [UIColor clearColor];
        _bottomScrollView.tag = 999;
    }
    _bottomScrollView.contentSize = CGSizeMake(0, KSCREENHEIGHT - NavigationMagin+100);
    return _bottomScrollView;
}

- (NSMutableArray *)dataSourceArray
{
    if (_dataSourceArray == nil)
    {
        _dataSourceArray = [NSMutableArray new];
    }
    return _dataSourceArray;
}

- (IGCreatListApi *)creatListApi
{
    if (_creatListApi == nil)
    {
        _creatListApi = [IGCreatListApi new];
    }
    return _creatListApi;
}

#pragma mark - 收键盘
-(void)keyboardHide:(UITapGestureRecognizer*)tap
{
    [self.nameTextField resignFirstResponder];
    [self.personInfoTextView resignFirstResponder];
}

- (void)ig_leftBackButtonPressed:(id)sender
{
    [super ig_leftBackButtonPressed:sender];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"EditDrawPic" object:nil];
}

@end


















